package com.yrxy.thread.case6;

import java.util.concurrent.atomic.AtomicInteger;

public class Account {
    // 声明一个原子类, 多个线程操作这个变量是线程安全的
    private AtomicInteger amount;

    private String name;

    public void name() {
        System.out.println("账户为：" + name + "!");
    }

    /**
     * 存款方法
     */
    public synchronized boolean deposit(String threadName, int change) {

        amount.addAndGet(change);
        // 账户余额上限是20000元 ,超过金额就不让存了
        if (amount.get() > 20000) {
            System.out.print("存款金额已经达到上限，存款失败");
            return false;
        }
        System.out.println("01：" + threadName + ",存款金额为" + change + ",开始存款，存款后余额为" + amount);
        return true;
    }

    /**
     * 取款
     */
    public synchronized boolean withdraw(String threadName, int money) {
        if (amount.get() <= 0 || amount.get() < money) {  // 如果取款金额大于账户的余额
            System.out.println(threadName + ",账户金额为" + amount.get() + "，你的取款金额为" + money + "，取款失败");
            return false;
        } else {
            amount.addAndGet(-money);  //取款操作
            System.out.println("02：" + threadName + ",取款金额为" + money + ",开始取款，取款后余额为" + amount);
            return true;
        }
    }

    /**
     * 开户
     */
    public void openAccount(String name, Integer money) {
        this.name = name;
        this.amount = new AtomicInteger(money);
        System.out.println("00：" + name + "开户成功,开户金额为" + money);
    }

    public AtomicInteger getAmount() {
        return amount;
    }

//    public void setAmount(AtomicInteger amount) {
//        this.amount = amount;
//    }
}
